<?php
/*
 * Copyright (c) 2008 Sergey Bondari, bondari@bondari.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * - The name of the author may not be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

namespace Mosaic\System;



/**
 * Library base class for generic request broker
 *
 * Generic request broker implementation. 
 * Request pools, queues, resource enumeration
 *
 * @package System
 * @subpackage Node
 */
abstract class GenericRequestBroker {
	/**
	 * Main server socket of the node
	 * @var stream
	 */
	protected $extSocket;

	/**
	 * Set of all active sockets
	 * @var array
	 */
	protected $sockets = array();
	

	/**
	 * Request queue indexed with request ticket
	 * array(socketID, objectToSend)
	 * @var array
	 */
	protected $queue = array();


	/**
	 * Pool of requests per socket
	 * array(socketID => array(RequestToken => array(REQUEST, RESPONSE))
	 * @var array
	 */
	protected $pool = array();


	/**
	 * Default constructor
	 */
	function __construct() {

	}

	/**
	 * Request broker server loop
	 */
	abstract public function run();
	
	/**
	 * Incoming request processing
	 *
	 * @param \Mosaic\System\Request
	 * @param integer ID of the socket
	 */
	abstract protected function processRequest(Request $req, $socketID);



	/**
	 * Response processing. 
	 * Releases request pool and adds response to queue
	 */
	protected function processResponse(Response $res, $socketID) {
		global $sys;
		if (isset($this->pool[$res->getRequestToken()])) {
			trigger_error('Processing response to request  '. $res->getRequestToken());
			$this->queue[$this->pool[$res->getRequestToken()][0]]->insert($res, 5);
			unset($this->pool[$res->getRequestToken()]);
		} else {
			trigger_error('Unknown request for this response. Response dropped. Token: '.$res->getRequestToken());
		}
	}



	/**
	 * Assigns unique integer to the socket
	 */
	protected function registerSocket($socket, $protocol = \Mosaic\MCGI\MCGI) {
		static $cnt = 0;
		$cnt++;
		$this->sockets[$cnt] = array($socket, $protocol);
		
		$this->pool[$cnt] = array();
		$this->queue[$cnt] = new \SplPriorityQueue();
		$this->queue[$cnt]->setExtractFlags(\SplPriorityQueue::EXTR_DATA);

		trigger_error('Socket '.$socket.' is registered with ID'.$cnt);
		return $cnt;
	}

	/**
	 * Releases all queues and pools. Closes socket.
	 */
	protected function unregisterSocket($socket) {
		trigger_error('Unregistering socket '.$socket);
		if (is_resource($socket)) {
			$socketID = $this->socketId($socket);
		} else {
			$socketID = $socket;
			$socket = $this->socket($socketID);
		}
		unset($this->sockets[$socketID]);
		unset($this->pool[$socketID]);
		unset($this->queue[$socketID]);
		fclose($socket);
	}

	/**
	 * Returns an integer index of a socket
	 */
	protected function socketId($socket) {
		foreach ($this->sockets as $id => $_s) if ($_s[0] == $socket) return $id;
		trigger_error('Could not find socket ID for socket '. $socket, E_USER_ERROR);
		return false;
	}

	/**
	 * Returns a socket based on the integer index
	 */
	protected function socket($socketId) {
		if (isset($this->sockets[$socketId])) {
			return $this->sockets[$socketId][0];
		} else {
			throw new RuntimeException('Socket with ID '. $socketId.' does not exist');
		}
	}

	/**
	 * Returns a socket protocol version based on the integer index
	 */
	protected function socketProtocol($socketId) {
		if (isset($this->sockets[$socketId])) {
			return $this->sockets[$socketId][1];
		} else {
			throw new RuntimeException('Socket with ID '. $socketId.' does not exist');
		}
	}


	/**
	 * @param integer Request origin socket id
	 * @param Request
	 * @param Response
	 */
	protected function pool($origin, Request $req, Response $res = NULL) {
		$this->pool[$req->getRequestToken()] = array($origin, $req, $res);
	}

	protected function enqueue($destination, ifRequestEntity $r, $priority = 10) {
		$this->queue[$destination]->insert($r,$priority);
	}


	
}
